import React,{ useState, useEffect } from "react";
import './index.scss'
import { Input,Button,Table,Modal,message } from "antd";
import { PlusOutlined,MenuUnfoldOutlined } from '@ant-design/icons'; //5.20 版本的使用方式
import { getRoleApi,getUsersByRole,addRoleApi,searchRoleApi,delRoleApi } from '../../../api/role'
import AddUser from "./addUser";
const Role = () => {
  const [roleList, setRoleList] = useState([]) //角色列表
  const [currentRole, setCurrentRole] = useState({id:'',name:''}) //当前角色
  const [userList, setUserList] = useState([]) //用户列表
  const [roleKeyWord, setRoleKeyWord] = useState('') //角色关键字
  const [isAddUser, setIsAddUser] = useState(false)
  const [selectUserId, setSelectUserId] = useState([])
  const getRole = async ()=>{
    const res = await getRoleApi({name:roleKeyWord})
    setRoleList(res.data)
    clickRole(res.data[0])
  }
  useEffect(()=>{
    getRole()
  },[])
  // 搜索角色
  const searchRole = async () => {
    const param = { name: roleKeyWord }
    const res = await searchRoleApi(param)
    if (res.code === 200) {
      setRoleList(res.data)
    }
  }
  // 点击角色
  const clickRole = async(item)=>{
    setCurrentRole(item)
    const res = await getUsersByRole({ id: item.id,})
    if (res.code === 200) {
      setUserList(res.data)
    }
  }
  const [left, setLeft] = useState(0) //左侧滚动条位置
  const [top, setTop] = useState(0) //左侧滚动条位置
  const [showContext, setShowContext] = useState(false) //是否显示操作菜单
  const [currentData, setCurrentData] = useState({}) //当前操作的角色
  const openOperateRole = (e,item)=>{
    e.stopPropagation(); //阻止事件冒泡
    setShowContext(true)
    setLeft(e.clientX - 130)
    setTop(e.clientY + 10)
    setCurrentData(item)
  }
  document.addEventListener('click', function (e) {
    setShowContext(false)
  })
  const [operatrRoleType, setOperatrRoleType] = useState('') //操作类型
  const [isModalOpen, setIsModalOpen] = useState(false); //是否显编辑角色示弹窗
  const [inputValue, setInputValue] = useState(''); //输入框的值
  const operateRole = (type) => {
    setIsModalOpen(true)
    setInputValue(currentData.name)
    if (type === 'edit') {
      setOperatrRoleType('编辑角色')
    }
    if (type === 'add') {
      setOperatrRoleType('添加角色')
    }
  }
  // 2.添加角色或编辑角色
  const addRole = async () => {
    const param = { name:inputValue,id: currentData.id}
    const res = await addRoleApi(param)
    if (res.code === 200) {
      setIsModalOpen(false)
      currentData.id ? message.success('编辑成功'):message.success('添加成功')
      getRole()
    }
  }
  const closeModel = () => {
    setIsModalOpen(false)
  }
  // 删除角色
  const deleteRole = async () => {
    console.log(currentData)
    const res = await delRoleApi({ id: currentData.id })
    if (res.code === 200) {
      message.success('删除成功')
      getRole()
    }
  }
  // 添加用户
  const handleAdd = () => {
    setIsAddUser(true)
    console.log(userList)
    const arr = userList.map(item=>item.id)
    setSelectUserId(arr)
  }
  const columns =[
    {
      title: '用户名',
      dataIndex: 'name',
    },
    {
      title: '密码',
      dataIndex: 'pwd',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: '电话',
      dataIndex: 'tel',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
    },
  ]
  //newData 子组件传过来的值
  const childUpdateData = (isModalOpen,user) => {
    setIsAddUser(isModalOpen)
    console.log(user)
  }
  return (
    <div className="role-box">
        <div className="left">
          <div className="header">
            <Input placeholder="请输入角色名称" value={roleKeyWord} 
            onChange={( e ) => {
              setRoleKeyWord(e.target.value)
            }}
            onPressEnter={( e ) => searchRole()}
            />
            <PlusOutlined onClick={()=>operateRole('add')}/>
          </div>
          <div className="content">
            {
              roleList.map( item=>{
                return (
                  <div className={currentRole.id === item.id ? 'role-item current' : 'role-item'} 
                  onClick={(e)=>clickRole(item)} 
                  key={item.id}
                  >
                    <span className="text" > { item.name }</span>
                    <MenuUnfoldOutlined className="icon" onClick={(e)=>openOperateRole(e,item)}/>
                  </div>
                )
              })
            }
            {
              showContext &&
              <ul className="context" style={{left:left,top:top}}>
                <li className="item" onClick={()=>operateRole('edit')}>编辑角色</li>
                <li className="item" onClick={()=>deleteRole()}>删除角色</li>
              </ul>
            }
          </div>
        </div>
        <div className="right">
          <div className="header">{ currentRole.name }</div>
          <div className="search">
            <div><Input placeholder="请输入用户名称"/></div>
            <div><Button type="primary" onClick={()=>handleAdd()}>添加用户</Button></div>
          </div>
          <div className="table-box">
            <Table dataSource={userList} columns={columns} pagination={false} rowKey={'id'}/>;
          </div>
        </div>
        <Modal title={operatrRoleType} open={isModalOpen} onOk={addRole} onCancel={closeModel}>
          <p>请输入角色名称</p>
          <Input placeholder="请输入角色名称" value={inputValue} onChange={(e) => setInputValue(e.target.value)}/>
        </Modal>
        {isAddUser &&<AddUser visible={isAddUser} selectUserId={selectUserId} updateData={childUpdateData}></AddUser>}
     </div>
  )
}
export default Role